package com.ttc.mBackupK16.BackupPhotos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ttc.mBackupK16.R;
import com.ttc.mBackupK16.BackupPhotos.SelectedListActivity.QueueAdapter.QueueItem;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SelectedListActivity extends Activity {
	private QueueAdapter queueAdapter;
	private ListView zipList;
	private ProgressDialog progressDialog;
	private static final int PROGRESSDIALOG_ID = 0;
	private static final int BACKUP_FILE_NAME_DIALOG = 1;
	private static final int CANCELED = -4;
	private Zipper zipper;
	int currentProcess;
	private String currentStatus = "Zipping images....";
	private ArrayList<Integer> ids;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.uploadqueue);

		queueAdapter = new QueueAdapter();
		// String ids = getIntent().getStringExtra("Ids");
		ids = getIntent().getIntegerArrayListExtra("Ids");
		queueAdapter.initialize(ids);
		zipList = (ListView) findViewById(R.id.UploadList);
		zipList.setItemsCanFocus(true);
		zipList.setAdapter(queueAdapter);

		Button btnZipImage = (Button) findViewById(R.id.StartUploadBtn);
		btnZipImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showFileNameDialog();
			}
		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case PROGRESSDIALOG_ID:
			removeDialog(PROGRESSDIALOG_ID);
			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setMax(queueAdapter.getUploadCount());
			progressDialog.setTitle("Zipping....");
			progressDialog.setCancelable(true);
			progressDialog.setMessage(currentStatus);
			progressDialog.setProgress(currentProcess);
			progressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					if (zipper != null
							&& zipper.getStatus() != AsyncTask.Status.FINISHED) {
						zipper.cancel(true);
					}
				}
			});
			break;
		case BACKUP_FILE_NAME_DIALOG:

			break;

		default:
			progressDialog = null;
		}

		return progressDialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		switch (id) {
		case PROGRESSDIALOG_ID:
			if (zipper != null && zipper.getStatus() != Status.FINISHED) {
				zipper.cancel(true);

			}
		}
		super.onPrepareDialog(id, dialog);
	}

	public void showFileNameDialog() {
		final Dialog dialog = new Dialog(this, R.style.WideDialogTheme);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.i_custom_dialog);
		dialog.setTitle("Enter Backup file name");
		final EditText txtContent = (EditText) dialog
				.findViewById(R.id.i_custom_dialog_txtContent);

		Button btnOk = (Button) dialog.findViewById(R.id.i_custom_dialog_btnOK);
		Button btnCancel = (Button) dialog
				.findViewById(R.id.i_custom_dialog_btnCancel);

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});

		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String backupFileName = txtContent.getText().toString();
				// btnFileName.setText("Backup name: " + backupFileName);

				showDialog(PROGRESSDIALOG_ID);

				ArrayList<String> paths = new ArrayList<String>();
				for (QueueItem item : queueAdapter.queueItems) {
					paths.add(item.path);
				}
				zipper = new Zipper(paths, backupFileName);
				zipper.execute();
				dialog.cancel();
			}
		});
		dialog.show();
	}

	public class QueueAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		public ArrayList<QueueItem> queueItems = new ArrayList<QueueItem>();

		public QueueAdapter() {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void initialize(ArrayList<Integer> ids) {
			queueItems.clear();
			// String[] arrIds = ids.split(",");
			for (int item : ids) {
				QueueItem queueItem = new QueueItem();
				queueItem.mediaId = item;
				final String[] columns = { MediaStore.Images.Media.DATA };
				final String orderBy = MediaStore.Images.Media._ID;
				Cursor imageCursor = managedQuery(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
						MediaStore.Images.Media._ID + " = " + queueItem.mediaId
								+ "", null, orderBy);

				for (int i = 0; i < imageCursor.getCount(); i++) {
					imageCursor.moveToPosition(i);
					int dataColumIndex = imageCursor
							.getColumnIndex(MediaStore.Images.Media.DATA);
					queueItem.path = imageCursor.getString(dataColumIndex);
				}
				imageCursor.close();
				queueItems.add(queueItem);
			}
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {

			return queueItems.size();
		}

		public int getUploadCount() {
			int count = 0;
			for (QueueItem item : queueItems) {
				if (item.uploaded != 1) {
					count++;
				}
			}
			return count;
		}

		@Override
		public QueueItem getItem(int position) {

			return queueItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.uploadqueueitem, null);
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.QueueItemThumbnail);
				holder.caption = (EditText) convertView
						.findViewById(R.id.QueueItemCaption);
				holder.status = (TextView) convertView
						.findViewById(R.id.uploadStatus);

				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			QueueItem item = getItem(position);

			final String[] columns = { MediaStore.Images.Media.DATA,
					MediaStore.Images.Media.DISPLAY_NAME };
			final String orderBy = MediaStore.Images.Media._ID;
			Cursor imageCursor = managedQuery(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
					MediaStore.Images.Media._ID + " = " + item.mediaId + "",
					null, orderBy);
			for (int i = 0; i < imageCursor.getCount(); i++) {
				imageCursor.moveToPosition(i);
				holder.imageView.setImageBitmap(MediaStore.Images.Thumbnails
						.getThumbnail(getContentResolver(), item.mediaId,
								MediaStore.Images.Thumbnails.MICRO_KIND, null));
				int image_column_index = imageCursor
						.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
				String fileName = imageCursor.getString(image_column_index);
				item.caption = fileName;
			}
			imageCursor.close();
			if (item.uploaded == 1) {
				holder.status.setText("Uploaded");
			} else if (item.uploaded == 0) {
				holder.status.setText("Pending");
			} else {
				holder.status.setText("Failed");
			}
			holder.caption.setId(position);
			holder.caption.setText(item.caption);
			holder.caption
					.setOnFocusChangeListener(new OnFocusChangeListener() {

						@Override
						public void onFocusChange(View v, boolean hasFocus) {
							if (!hasFocus) {
								final int position = v.getId();
								final EditText Caption = (EditText) v;
								queueAdapter.queueItems.get(position).caption = Caption
										.getText().toString();
							}

						}

					});

			return convertView;
		}

		public class ViewHolder {
			ImageView imageView;
			EditText caption;
			TextView status;
			TextView fileName;
		}

		public class QueueItem {
			String path;
			long mediaId;
			String caption;
			int uploaded;
		}

	}

	public class Zipper extends AsyncTask<Void, String, String> {

		private ArrayList<String> filesToZip;
		private String zipFileName;
		private String zipFile;
		private ProgressDialog mProgress;
		private Context context;
		public boolean isFinished = false;

		public Zipper(ArrayList<String> filesToZip, String zipFileName) {

			this.filesToZip = filesToZip;
			this.zipFileName = zipFileName;

		}

		@Override
		protected String doInBackground(Void... params) {
			String result = "";
			zipFileName += ".zip";
			try {

				String root = Environment.getExternalStorageDirectory()
						.toString();
				String zipFile = root + "/mBackup2";

				File dir = new File(zipFile);
				if (!dir.exists())
					dir.mkdirs();

				zipFile = zipFile + "/" + zipFileName;

				Log.i("mediastore", "ZIPFILE: " + zipFile);
				byte[] buffer = new byte[1024];

				File f = new File(zipFile);
				// if (f.delete() == true)
				// Log.v("mediastore", "Deleted");
				if (!f.exists())
					f.createNewFile();

				FileOutputStream fout = new FileOutputStream(f);

				ZipOutputStream zout = new ZipOutputStream(fout);
				// zout.setLevel(6);

				int n = filesToZip.size();
				FileInputStream fin;
				ZipEntry zipEntry;
				for (int i = 0; i < n; i++) {

					fin = new FileInputStream(filesToZip.get(i));
					zipEntry = new ZipEntry(filesToZip.get(i));

					zout.putNextEntry(zipEntry);

					int length;

					while ((length = fin.read(buffer)) > 0) {
						zout.write(buffer, 0, length);
					}

					zout.closeEntry();
					fin.close();

					// update process
					currentProcess = i + 1;

					String filePath = zipEntry.getName();
					String fileName = filePath.substring(
							filePath.lastIndexOf("/") + 1, filePath.length());

					currentStatus = "Adding: " + fileName;
					publishProgress(new String[] { "Adding: " + fileName });
				}

				// close the ZipOutputStream
				publishProgress(new String[] { "Saving backup file..." });
				zout.flush();
				zout.close();

				result = "Finished";
			} catch (IOException ioe) {
				Log.v("mediastore",
						"Error at ZipFlie.doinBackGround: " + ioe.getMessage());
				result = "Error";
				// FileManager.deleteFile(zipFile);
				if (mProgress != null) {
					mProgress.dismiss();
					mProgress = null;
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			isFinished = true;
			Toast.makeText(getApplicationContext(), "Finished",
					Toast.LENGTH_SHORT).show();

			if (progressDialog != null) {
				progressDialog.dismiss();
				progressDialog = null;
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			progressDialog.setMessage(values[0]);
			progressDialog.setProgress(currentProcess);
			super.onProgressUpdate(values);
		}

	}

}
